import 'dart:convert';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:goumao_app/Controller/gm_article_detail.dart';
import 'package:goumao_app/Customs/gm_app_util.dart';
import 'package:goumao_app/Model/gm_article_model.dart';
import 'package:goumao_app/Model/gm_index_model.dart';

import '../Model/gm_anim_video_model.dart';
import 'gm_anivideo_detail.dart';
import 'gm_chat_ui.dart';

Widget hotSmallCircle(GMIndexData mydata, BuildContext context) {
  return Column(
    children: [
      SizedBox(
        height: 89.5,
        child: Row(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image.network(
                mydata.coverImage!,
                width: 70,
                height: 70,
                fit: BoxFit.cover,
              ),
            ),
            const SizedBox(
              width: 10,
            ),
            Expanded(
              child: SizedBox(
                height: 62,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      mydata.circleName!,
                      style: const TextStyle(
                          color: Color(0xff1a1a1a),
                          fontSize: 15,
                          fontWeight: FontWeight.w600),
                    ),
                    Text(mydata.brief !=null?mydata.brief!:"",
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          color: Color(0xff666666),
                          fontSize: 12,
                        )),
                    Text('${mydata.joinCount}个成员',
                        style: const TextStyle(
                          color: Color(0xff666666),
                          fontSize: 12,
                        ))
                  ],
                ),
              ),
            ),
            const SizedBox(
              width: 12,
            ),
            InkWell(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => GMChatPage(
                      indexData: mydata,
                      title: mydata.circleName,
                    ),
                  ),
                );
              },
              child: Image.asset(
                "assets/images/gm_fs_xx_icon@2x.png",
                width: 38,
                height: 38,
              ),
            )
          ],
        ),
      ),
      const Divider(
        height: 0.5,
      )
    ],
  );
}

Widget hotArticle(GMArticleList mData, BuildContext context) {
  return InkWell(
    onTap: () {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => GMArticleDetailPage(
            article: mData,
          ),
        ),
      );
    },
    child: Container(
      padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6),
        color: const Color(0xffffffff),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                alignment: Alignment.center,
                height: 25,
                child: Row(
                  children: [
                    Visibility(
                        visible: int.parse(mData.type!) > 0,
                        child: Row(
                          children: [
                            Image.asset(
                              "assets/images/gm_wz_jp_icon@2x.png",
                              width: 15,
                            ),
                            const SizedBox(
                              width: 8,
                            ),
                          ],
                        )),
                    // ignore: unrelated_type_equality_checks
                    Visibility(
                      visible: mData.type == '2',
                      child: Row(
                        children: [
                          Image.asset(
                            'assets/images/gm_wz_vip_icon@2x.png',
                            width: 40,
                            height: 15,
                          ),
                          const SizedBox(
                            width: 8,
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: Text(
                  mData.title!,
                  style: const TextStyle(
                      color: Color(0xff000000),
                      fontSize: 16,
                      fontWeight: FontWeight.w800),
                ),
              )
            ],
          ),
          // Text(
          //   mData.title!,
          //   style: const TextStyle(
          //       color: Color(0xff000000),
          //       fontSize: 16,
          //       fontWeight: FontWeight.w800),
          // ),
          const SizedBox(
            height: 12,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Text(
                  mData.summary!,
                  maxLines: 4,
                  style: const TextStyle(
                      color: Color(0xff333333),
                      fontSize: 14,
                      fontWeight: FontWeight.w200),
                ),
              ),
              const SizedBox(
                width: 12,
              ),
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(
                  mData.coverImage!,
                  width: 100,
                  height: 74,
                  fit: BoxFit.cover,
                ),
              )
            ],
          )
        ],
      ),
    ),
  );
}

class GMIndexScreen extends StatefulWidget {
  const GMIndexScreen({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _GMIndexScreenState createState() => _GMIndexScreenState();
}

class _GMIndexScreenState extends State<GMIndexScreen> {
  // late final GMIndexModel indexModel;
  // late final GMArticleModel articleModel;
  late GMAnimVideoModel animVideoModel;

  List<String> topImages = [
    'assets/images/gm_banner_1@2x.png',
    'assets/images/gm_banner_2@2x.png'
  ];

  Future<GMIndexModel> _getIndexList() async {
    _gmGetVideoList();
    String jsonString = await rootBundle.loadString('assets/mydata/index.json');
    Map<String, dynamic> jsonData = json.decode(jsonString);
    var articleModel = GMIndexModel.fromJson(jsonData);
    return articleModel;
  }

  void _gmGetVideoList() async {
    String jsonString =
        await rootBundle.loadString('assets/mydata/gm_video_ani.json');
    Map<String, dynamic> jsonData = json.decode(jsonString);
    animVideoModel = GMAnimVideoModel.fromJson(jsonData);
  }

  Widget cellHeader(String title) {
    return InkWell(
      onTap: () {
        if (title == '热门文章') {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const GMArticleListPage(),
            ),
          );
        } else if (title == '趣聊小圈') {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const GMQuChatScreen(),
            ),
          );
        }
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: const TextStyle(
                color: Color(0xff1a1a1a),
                fontSize: 16,
                fontWeight: FontWeight.w700),
          ),
          Visibility(
              visible: title != '萌宠推荐',
              child: const Row(
                children: [
                  Text(
                    "更多",
                    style: TextStyle(color: Color(0xff333333), fontSize: 12),
                  ),
                  Icon(
                    Icons.chevron_right,
                    color: Colors.grey,
                  )
                ],
              ))
        ],
      ),
    );
  }

  Widget _animaTuijian(GMAnimData animData) {
    double tuijianW = (ScreenUtil().screenWidth - 32 - 24) / 3;
    double tuijianH = tuijianW * 4 / 3;
    return InkWell(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => GMAniVideoDetailApp(
              animaData: animData,
            ),
          ),
        );
      },
      child: Container(
        width: tuijianW + 12,
        padding: const EdgeInsets.only(right: 12),
        height: tuijianH,
        child: Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              bottomRight: Radius.circular(12.0),
              bottomLeft: Radius.circular(12.0),
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: NetworkImage(
                              'https://file.onepetmall.com/${animData.url!}'),
                          fit: BoxFit.cover)),
                  child: Image.asset("assets/images/gm_sy_play_icon.png"),
                ),
              ),
              Container(
                padding: const EdgeInsets.all(12),
                child: Text(
                  animData.text!,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                      color: Color(0xff1a1a1a),
                      fontSize: 14,
                      fontWeight: FontWeight.w400),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: GMAppUtil.navText("首页"),
      ),
      body: SafeArea(
          child: FutureBuilder<GMIndexModel>(
        future: _getIndexList(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const CircularProgressIndicator(); // 显示加载指示器
          } else if (snapshot.hasError) {
            return Text('Error: ${snapshot.error}');
          } else {
            GMIndexModel mModel = snapshot.data!;
            double tuijianW = (ScreenUtil().screenWidth - 32 - 24) / 3;
            double tuijianH = tuijianW * 4 / 3;
            return SingleChildScrollView(
              child: Container(
                padding: const EdgeInsets.fromLTRB(16, 16, 16, 30),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    CarouselSlider(
                        options: CarouselOptions(
                          height: 98,
                          autoPlay: true,
                          viewportFraction: 1.0,
                          enlargeCenterPage: false,
                        ),
                        items: topImages.map((String file) {
                          return Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                            ),
                            width: ScreenUtil().screenWidth - 32,
                            child: Image.asset(
                              file,
                              height: 90,
                              fit: BoxFit.fill,
                            ),
                          );
                        }).toList()),
                    const SizedBox(
                      height: 20,
                    ),
                    cellHeader("趣聊小圈"),
                    const SizedBox(
                      height: 12,
                    ),
                    hotSmallCircle(mModel.data![0], context),
                    hotSmallCircle(mModel.data![1], context),
                    hotSmallCircle(mModel.data![2], context),
                    const SizedBox(
                      height: 20,
                    ),
                    cellHeader("萌宠推荐"),
                    const SizedBox(
                      height: 12,
                    ),
                    SizedBox(
                      height: tuijianH,
                      child: ListView.builder(
                          itemCount: animVideoModel.data!.length, // 列表总数
                          scrollDirection: Axis.horizontal,
                          itemBuilder: (context, index) =>
                              _animaTuijian(animVideoModel.data![index])),
                    ),
                    const SizedBox(
                      height: 12,
                    ),
                    cellHeader("热门文章"),
                    const SizedBox(
                      height: 12,
                    ),
                    hotArticle(mModel.article![0], context),
                    const SizedBox(
                      height: 6,
                    ),
                    hotArticle(mModel.article![1], context),
                    const SizedBox(
                      height: 6,
                    ),
                    hotArticle(mModel.article![2], context),
                    const SizedBox(
                      height: 6,
                    ),
                    hotArticle(mModel.article![3], context),
                    const SizedBox(
                      height: 6,
                    ),
                    hotArticle(mModel.article![4], context),
                    const SizedBox(
                      height: 6,
                    ),
                  ],
                ),
              ),
            );
          }
        },
      )),
    );
  }
}

class GMArticleListPage extends StatelessWidget {
  const GMArticleListPage({super.key});

  Future<GMArticleModel> _getArticleList() async {
    String jsonString =
        await rootBundle.loadString('assets/mydata/hot_crticle.json');
    Map<String, dynamic> jsonData = json.decode(jsonString);
    var articleModel = GMArticleModel.fromJson(jsonData);
    return articleModel;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: GMAppUtil.navText("热门文章"),
        elevation: 0,
      ),
      body: SafeArea(
        child: FutureBuilder<GMArticleModel>(
          future: _getArticleList(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const CircularProgressIndicator(); // 显示加载指示器
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              GMArticleModel mModel = snapshot.data!;
              return ListView.builder(
                  itemCount: mModel.data![0].list!.length, // 列表总数
                  itemBuilder: (context, index) =>
                      hotArticle(mModel.data![0].list![index], context));
            }
          },
        ),
      ),
    );
  }
}

class GMQuChatScreen extends StatefulWidget {
  const GMQuChatScreen({super.key});
  @override
  // ignore: library_private_types_in_public_api
  _GMQuChatScreenState createState() => _GMQuChatScreenState();
}

class _GMQuChatScreenState extends State<GMQuChatScreen> {
  List<GMIndexData> quchatDatasoure = [];

  void _getArticleList() async {
    String jsonString =
        await rootBundle.loadString('assets/mydata/gm_quchat.json');
    Map<String, dynamic> jsonData = json.decode(jsonString);
    var model = GMIndexModel.fromJson(jsonData);
    quchatDatasoure = model.data!;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    _getArticleList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: GMAppUtil.navText("小圈趣聊天"),
        elevation: 0,
      ),
      body: SafeArea(
          child: ListView.builder(
              itemCount: quchatDatasoure.length, // 列表总数
              itemBuilder: (context, index) {
                return Container(
                  padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
                  child: hotSmallCircle(quchatDatasoure[index], context),
                );
              })),
    );
  }
}
